//
//  GDMainHomeController.m
//  GraduationDesign
//
//  Created by JiaKang.Zhong on 16/1/3.
//  Copyright © 2016年 JiaKang.Zhong. All rights reserved.
//

#import "GDMainHomeController.h"
#import "MBProgressHUD+MJ.h"
#import <CoreLocation/CoreLocation.h>
#import "GDTrainStationController.h"
#import "GDBusStationController.h"
#import "GDWeatherController.h"
#import "GDAboutController.h"
#import "GDUserLoginController.h"
@interface GDMainHomeController ()<CLLocationManagerDelegate,UIScrollViewDelegate>
@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;
@property (weak, nonatomic) IBOutlet UIPageControl *pageControll;
- (IBAction)trainsViewClick:(id)sender;
- (IBAction)weatherViewClick:(id)sender;
- (IBAction)aboutViewClick:(id)sender;
- (IBAction)busStationViewClick:(id)sender;
- (IBAction)exitHomeController:(id)sender;
@property (nonatomic,strong)  CLLocationManager* locationManager;
/**
 *  用于接下来的城市定位
 */
@property (nonatomic,strong)  NSString* cityName;

/**
 *  定位度的保存
 */
@property (nonatomic,strong)  NSMutableDictionary* locationDic;
@end

#define  scrollViewNumber 3
@implementation GDMainHomeController

-(NSMutableDictionary *)locationDic{
    if (!_locationDic) {
        _locationDic = [NSMutableDictionary dictionary];
    }
    return _locationDic;
}
- (void)viewDidLoad {
    [super viewDidLoad];
        GDLog(@"%s",__func__);

    CGFloat imageViewY = self.scrollView.frame.size.height - 30;
    UIImageView * imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, imageViewY, GDScreenSize.size.width, 30)];
    imageView.image = [UIImage imageNamed:@"home_whiteBlock"];
    imageView.alpha = 0.5;
    [self.view addSubview:imageView];
    
    self.scrollView.delegate = self;
    // 图片浏览器展示当前的app数据
    // 动态创建imageView并添加到scrollView中
    CGFloat imgW = GDScreenSize.size.width;
    CGFloat imgH = self.scrollView.frame.size.height;
    CGFloat imgY = 0;
    
    for (int i = 0; i < scrollViewNumber; i++) {
        UIImageView * imageView = [[UIImageView alloc] init];
        
        //设置frame值
        CGFloat x=i *  imgW ;
        imageView.frame = CGRectMake(x, imgY, imgW, imgH);
        NSString *strC = [[NSBundle mainBundle] pathForResource:[NSString stringWithFormat:@"main_scrollview%d.jpg",(i+ 1)] ofType:nil];
        imageView.image = [UIImage imageWithContentsOfFile:strC];
        //添加到父控件中
        [self.scrollView addSubview:imageView];
        
    }
    //设定滚动的内容
    self.scrollView.contentSize = CGSizeMake(imgW * scrollViewNumber, 0);
    //设置分页显示
    self.scrollView.pagingEnabled = YES;
    //设置pageView的总页数
    self.pageControll.numberOfPages = 3;
    //设置pageView的当前页数，默认下标从0开始
    self.pageControll.currentPage = 0;
    //隐藏滚动条
    self.scrollView.showsHorizontalScrollIndicator = NO;
    self.scrollView.showsVerticalScrollIndicator = NO;
    //启动一个定时器
    [NSTimer scheduledTimerWithTimeInterval:3.0 target:self
                                   selector:@selector(ScrollImage) userInfo:nil repeats:YES];
    
#pragma mark 开启定位
    [self initLocationManager];
}

//滚动方法
-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    //计算滚动的页数
    CGFloat offsetX = scrollView.contentOffset.x + scrollView.frame.size.width / 2;
    int page = offsetX / scrollView.frame.size.width;
    
    //给pageView设定当前的页数
    self.pageControll.currentPage = page;
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)ScrollImage{
    
    //1.获取到当前的页数

    NSInteger page = self.pageControll.currentPage;
    if (page == self.pageControll.numberOfPages - 1) {
        page = 0;
    }else{
        page ++;
    }
    self.pageControll.currentPage = page;
    // 3. 用每页的宽度 * (页码 + 1) == 计算除了下一页的contentOffset.x
    CGFloat offsetX = page * self.scrollView.frame.size.width;
    
    // 4. 设置UIScrollView的contentOffset等于新的偏移的值
    [self.scrollView setContentOffset:CGPointMake(offsetX, 0) animated:YES];
    
    
}

#pragma mark 开始定位
-(void) initLocationManager{
    [MBProgressHUD showMessage:@"正在为你定位当前的城市..." toView:self.view];
    // 判断定位操作是否被允许
    if([CLLocationManager locationServicesEnabled]) {
        self.locationManager = [[CLLocationManager alloc] init] ;
        self.locationManager.delegate = self;
        //在ios 8.0下要授权
        if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0){
            //  [self.locationManager requestWhenInUseAuthorization];// 前台定位
            [_locationManager requestAlwaysAuthorization];// 前后台同时定位
        }
    }else {
        [MBProgressHUD hideHUDForView:self.view];
        //提示用户无法进行定位操作
        UIAlertView *alertView = [[UIAlertView alloc]initWithTitle: @"提示" message:@"定位不成功 ,请确认开启定位" delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
        [alertView show];
    }
    // 开始定位
    [self.locationManager startUpdatingLocation];
    
    
}

#pragma mark 定位回调
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations{
   
    //此处locations存储了持续更新的位置坐标值，取最后一个值为最新位置，如果不想让其持续更新位置，则在此方法中获取到一个值之后让locationManager stopUpdatingLocation
    CLLocation *currentLocation = [locations lastObject];
    CLGeocoder * geoCoder = [[CLGeocoder alloc] init];
    GDLog(@"%@",[NSString stringWithFormat:@"经度:%3.5f\n纬度:%3.5f",currentLocation.coordinate.latitude,currentLocation.coordinate.longitude]);
    [self.locationDic setValue:[NSString stringWithFormat:@"%f",currentLocation.coordinate.latitude] forKey:@"latitude"];
      [self.locationDic setValue:[NSString stringWithFormat:@"%f",currentLocation.coordinate.longitude] forKey:@"longitude"];
    // 烦序列化解析数据
    [geoCoder reverseGeocodeLocation:currentLocation completionHandler:^(NSArray *placemarks, NSError *error) {
        if (placemarks.count > 0) {
            [MBProgressHUD hideHUDForView:self.view];
             [self.locationManager stopUpdatingLocation];
            for (CLPlacemark * placemark in placemarks) {
                NSDictionary *test = [placemark addressDictionary];
//                GDLog(@"%@",test);
                self.cityName = [test objectForKey:@"City"];
               NSRange cityRange =  [self.cityName rangeOfString:@"市"];
                self.cityName = [self.cityName substringToIndex:cityRange.location];
//                self.cityName = @"珠海";
            }
            if (self.cityName != nil) {
                [MBProgressHUD showSuccess:[NSString stringWithFormat:@"定位成功，当前的城市为:%@",self.cityName] toView:self.view];
            }
            if (error) {
                [MBProgressHUD showError:[NSString stringWithFormat:@"%@",error] toView:self.view];

            }
        }}];
}


-(BOOL)prefersStatusBarHidden{
    return YES;
}

#pragma mark  ****************  进入列车界面   ****************
- (IBAction)trainsViewClick:(id)sender {
    GDTrainStationController * trainStationController = [[GDTrainStationController alloc] init];
//        UINavigationController * navController = [[UINavigationController alloc] initWithRootViewController:trainStationController];
    [self presentViewController:trainStationController animated:YES completion:nil];
    
}

#pragma mark  ****************  进入天气界面   **************** 存在返回按钮
- (IBAction)weatherViewClick:(id)sender {
        GDWeatherController * weatherController = [[GDWeatherController alloc] init];
    weatherController.cityName = self.cityName;
    [self presentViewController:weatherController animated:YES completion:nil];
}

#pragma mark  ****************  进入关于界面   ****************
- (IBAction)aboutViewClick:(id)sender {
    
    GDAboutController * aboutController = [[GDAboutController alloc] init];
//    UINavigationController * navController = [[UINavigationController alloc] initWithRootViewController:aboutController];
    [self presentViewController:aboutController animated:YES completion:nil];
   
}

#pragma mark  ****************  进入公交界面   ****************
- (IBAction)busStationViewClick:(id)sender {
    GDBusStationController * busStationController = [[GDBusStationController alloc] init];
    busStationController.cityName = self.cityName;
    busStationController.location = self.locationDic;
    UINavigationController * navController = [[UINavigationController alloc] initWithRootViewController:busStationController];
     [self presentViewController:navController animated:YES completion:nil];
}

- (IBAction)exitHomeController:(id)sender {
    
     GDUserLoginController* userLoginController = [[ GDUserLoginController alloc] init];
    [UIApplication sharedApplication].keyWindow.rootViewController = userLoginController;
}
@end
